package local.kexnichi.appengine.gcalfinance.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import local.kexnichi.appengine.gcalfinance.utility.Utility;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeCallbackServlet;
import com.google.appengine.api.users.UserServiceFactory;

public class CallbackServlet extends
        AbstractAppEngineAuthorizationCodeCallbackServlet {

    @Override
    protected void onSuccess(HttpServletRequest request,
            HttpServletResponse response, Credential credential)
            throws ServletException, IOException {
        response.sendRedirect("/");
    }

    @Override
    protected void onError(HttpServletRequest request,
            HttpServletResponse response,
            AuthorizationCodeResponseUrl errorResponse)
            throws ServletException, IOException {
        String nickname = UserServiceFactory.getUserService().getCurrentUser()
                .getNickname();
        response.getWriter().print(
                "<h3>" + nickname
                        + ", why don't you want to play with me?</h1>");
        response.setStatus(200);
        response.addHeader("Content-Type", "text/html");
    }

    @Override
    protected AuthorizationCodeFlow initializeFlow() throws ServletException,
            IOException {
        return Utility.initializeFlow();
    }

    @Override
    protected String getRedirectUri(HttpServletRequest request)
            throws ServletException, IOException {
        return Utility.getRedirectUri(request);
    }

}
